package com.bw.controller;

import com.alibaba.fastjson.JSONObject;
import com.bw.entity.User;
import com.bw.mapper.UserMapper;
import org.spring.kun.common.GiteeUtils;
import org.spring.kun.common.Md5Utils;
import org.spring.kun.common.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;

@Controller
public class GiteeLoginController {

        @Autowired
    UserMapper userMapper;
    @RequestMapping("/callbackCode.do")
    public String callback(String code, HttpServletResponse response, Model model){

        System.out.println("接收到的临时授权码  " + code) ;

        String tokenByCode = GiteeUtils.getAccessTokenByCode(code);
        System.out.println("获取到的token  " + tokenByCode) ;

        JSONObject userInfoByToken = GiteeUtils.getGiteeUserInfoByToken(tokenByCode);
        System.out.println("获取到的用户资料  " + userInfoByToken.toJSONString()) ;

        // 解析出4个字段 存到数据库里 进行注册  ： 个人空间地址  昵称  头像  主键id

        String nickName = userInfoByToken.getString("name");
        String name = userInfoByToken.getString("login");
        String avatarUrl = userInfoByToken.getString("avatar_url");
        Integer giteeId = userInfoByToken.getInteger("id");

        User userDB = userMapper.selectByName(name);
        if (userDB == null){

            userDB = new User();
            userDB.setName(name);
            userDB.setNickName(nickName);
            userDB.setAvatarUrl(avatarUrl);
            userDB.setGiteeId(giteeId);
            userMapper.addUser(userDB);
        }

        // 颁发令牌
        // 加密用户信息 得到token， 把token放入cookie, 把cookie返回给浏览器，  设置令牌的有效期30分钟，cookie的有效期 30分钟
        TokenUtils.responseTokenByCookie(userDB,response,30);


        return "redirect:list.do";

    }
}
